package com.group.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.eclipse.jetty.util.UrlEncoded;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.base.view.ListResult;
import com.group.model.*;
import com.group.util.NoteException;
import com.group.util.WeiXinUtils;

/**
 * 竞猜接口
 * 
 * @author zhaolei
 *
 */
@Controller
public class GuessController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(GuessController.class);

	/**
	 * 添加/编辑 竞猜
	 * 
	 * @param guess
	 * @return
	 */
	@PostMapping(value = "/guess/add")
	@ResponseBody
	public GeneralResult<Guess> addGuess(@RequestBody Guess guess) {
		// if ("已封盘".equals(guess.getState()) || "下注中".equals(guess.getState()))
		// {
		// int count = guessDao.countInProgressGuess(guess.getId());
		// if (count >= 1) {
		// throw new NoteException("只能有一个进行中的竞猜");
		// }
		// }

		beanDao.save(guess);

		for (GuessInfo info : guess.getInfos()) {
			info.setGuessId(guess.getId());
			beanDao.save(info);
		}

		return new GeneralResult<Guess>().setValue(guess);
	}

	/**
	 * 查询竞猜列表
	 * 
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping(value = "/guess/query")
	@ResponseBody
	public ListResult<Guess> updateGuess(Integer start, Integer limit) {

		return new ListResult<Guess>().setList(guessDao.queryGuess(start, limit)).setTotal(guessDao.queryGuessCount());
	}

	/**
	 * 查询微信页面要显示的竞猜
	 * 
	 * @param userId
	 *            如果传用户id 会显示用户是否有红包要领的状态
	 * 
	 * @return
	 */
	@GetMapping(value = "/guess/query/show")
	@ResponseBody
	public GeneralResult<Guess> getShowGuess(Long userId) {
		Guess guess = beanDao.quickQueryOne(Guess.class, "show", 1);
		if (guess == null) {
			return new GeneralResult<>();
		}
		guess.setInfos(beanDao.quickQueryList(GuessInfo.class, "guessId", guess.getId()));

		if (userId != null && guess != null) {
			guess.setHasRedPack(false);
			GuessRedPack para = new GuessRedPack();
			para.setUserId(userId);
			para.setGuessId(guess.getId());
			para.setSend(0);
			GuessRedPack exist = beanDao.queryOne(para);
			if (exist != null) {
				guess.setHasRedPack(true);
			}
		}

		return new GeneralResult<Guess>().setValue(guess);
	}

	/**
	 * 发送红包
	 * 
	 * @param guessId
	 * @param userId
	 * @return
	 */
	@GetMapping(value = "/guess/redpack/send")
	@ResponseBody
	public RedirectView sendRedPack(Long guessId, Long userId) {
		GuessRedPack para = new GuessRedPack();
		para.setUserId(userId);
		para.setGuessId(guessId);
		para.setSend(0);
		GuessRedPack exist = beanDao.queryOne(para);
		if (exist == null) {
			throw new NoteException("没有未领取的红包");
		}
		exist.setSend(1);
		beanDao.save(exist);

		int money = 100;
		String timeStamp = System.currentTimeMillis() + "";
		String code = "537c684c-a621-49b8-9a2e-a34feb532445";
		String str = "timeStamp=" + timeStamp + "&code=" + code + "&money=" + money;
		String md5Str = WeiXinUtils.getMD5Code(str);
		// String baseurl = getSystemParaValue("redpackurl");
		String redirectUrl = "http://hq.fourtrees.cn/guess/#/redpack";
		redirectUrl = UrlEncoded.encodeString(redirectUrl);

		String url = "http://pass2u.info/r/open/third/pay?timeStamp=" + timeStamp + "&redirectUrl=" + redirectUrl + "&echostr=" + md5Str + "&money=" + money;

		logger.info(" url = " + url);
		return new RedirectView(url);
	}

	/**
	 * 根据id查询详情
	 * 
	 * @param guessId
	 * @return
	 */
	@GetMapping(value = "/guess/query/id")
	@ResponseBody
	public GeneralResult<Guess> getById(Long guessId) {
		Guess guess = beanDao.quickQueryOne(Guess.class, "id", guessId);
		guess.setInfos(beanDao.quickQueryList(GuessInfo.class, "guessId", guessId));

		return new GeneralResult<Guess>().setValue(guess);
	}

	/**
	 * 删除竞猜
	 * 
	 * @param guessId
	 * @return
	 */
	@DeleteMapping(value = "/guess/delete/id")
	@ResponseBody
	public BaseResult deleteById(Long guessId) {
		beanDao.quickDeleteById(Guess.class, guessId);
		beanDao.quickDelete(GuessInfo.class, "guessId", guessId);
		return new BaseResult();
	}

	/**
	 * 设置竞猜为显示状态,其余的会变为不显示
	 * 
	 * @param guessId
	 * @return
	 */
	@GetMapping(value = "/guess/show/")
	@ResponseBody
	public BaseResult setShow(Long guessId) {
		// 设置其余的不显示
		guessDao.setUnShow(guessId);

		Guess guess = new Guess();
		guess.setId(guessId);
		guess.setShow(1);
		beanDao.save(guess);

		return new BaseResult();
	}

	/**
	 * 开盘,封盘 状态修改
	 * 
	 * @param guessId
	 * @param state
	 *            下注中,已封盘
	 * @return
	 */
	@GetMapping(value = "/guess/state/update")
	@ResponseBody
	public BaseResult updateState(Long guessId, String state) {
		Guess guess = new Guess();
		guess.setId(guessId);
		guess.setState(state);
		if ("下注中".equals(state))
			guess.setStartTime(new Date());
		if ("已封盘".equals(state))
			guess.setCloseTime(new Date());

		beanDao.save(guess);

		return new BaseResult();
	}

	/**
	 * 结算
	 * 
	 * @param guess
	 * @return
	 */
	@PostMapping(value = "/guess/state/settlement")
	@ResponseBody
	public synchronized BaseResult settlement(@RequestBody Guess guess) {
		Guess exist = beanDao.quickQueryOneById(Guess.class, guess.getId());
		if (exist.getState().equals("已结算"))
			throw new NoteException("不能重复结算");

		guess.setState("已结算");
		guess.setSettlementTime(new Date());
		beanDao.save(guess);
		// 红包发奖用户
		List<User> winUsers = new ArrayList<User>();

		// 结算币
		for (GuessInfo info : guess.getInfos()) {
			beanDao.save(info);
			// 查询用户投注记录
			List<GuessLog> logs = beanDao.quickQueryList(GuessLog.class, "guessInfoId", info.getId());

			for (GuessLog log : logs) {
				double rate = 0;
				if (info.getGuessResult().equals(info.getResult1()))
					rate = info.getRate1();
				else {
					rate = info.getRate2();
				}

				// 更新用户竞猜数据
				User user = beanDao.quickQueryOneById(User.class, log.getUserId());

				if (log.getResult().equals(info.getGuessResult())) {
					// 猜中
					log.setOpenResult("压中");
					log.setProfit(log.getAmount() * rate);
					user.setWin(user.getWin() + 1);
					user.setProfit(user.getProfit() + log.getProfit());
					if (!winUsers.contains(user))
						winUsers.add(user);
					// 增加钱包
					tickerService.addTicker(log.getUserId(), "wecc", log.getProfit(), "竞争活动中奖", null);
				} else {
					// 未猜中
					log.setOpenResult("未中");
					log.setProfit(-log.getAmount());
					user.setLoss(user.getLoss() + 1);
					user.setProfit(user.getProfit() - log.getAmount());
				}

				user.setWinRate(user.getWin().doubleValue() / (user.getWin().doubleValue() + user.getLoss()));
				beanDao.save(user);
				beanDao.save(log);

			}

		}

//		for (User user : winUsers) {
//			// 发红包
//			GuessRedPack rp = new GuessRedPack();
//			rp.setUserId(user.getId());
//			rp.setUserName(user.getName());
//			rp.setGuessId(guess.getId());
//			if (beanDao.queryOne(rp) == null) {
//				if (StringUtils.isNotEmpty(user.getQyOpenid())) {
//					// 直接发红包
//					rp.setSend(1);
//					redPackService.sendRedPack(100, user.getQyOpenid(), "芬果竞猜",user.getOpenid());
//				} else {
//
//				}
//
//				beanDao.save(rp);
//			}
//		}

		return new BaseResult();
	}

	/**
	 * 用户投注
	 * 
	 * @param guessInfoId
	 * @param result
	 *            结果字符串 , 比如 能 不能
	 * @param amount
	 *            数量
	 * @param userId
	 *            用户id
	 * @return
	 */
	@GetMapping(value = "/guess/select")
	@ResponseBody
	public GeneralResult<GuessInfo> select(Long guessInfoId, String result, Double amount, Long userId) {
		synchronized (guessInfoId) {
			UserTicker ut = tickerService.getUserTicker(userId, "wecc");
			if (ut == null || amount > ut.getNum())
				throw new NoteException("余额不足");

			GuessInfo info = beanDao.quickQueryOneById(GuessInfo.class, guessInfoId);
			if (info == null) {
				throw new NoteException("投注详情不存在");
			}

			Guess guess = beanDao.quickQueryOneById(Guess.class, info.getGuessId());
			if (!"下注中".equals(guess.getState())) {
				throw new NoteException("非下注中状态的竞猜不能下注");
			}

			// 添加用户抽奖日志
			GuessLog log = new GuessLog();
			log.setUserId(userId);
			log.setGuessInfoId(guessInfoId);
			if (beanDao.queryOne(log) != null) {
				throw new NoteException("不能重复投注");
			}
			log.setAmount(amount);
			log.setGuessId(info.getGuessId());
			log.setOpenResult("竞猜中");
			log.setResult(result);
			beanDao.save(log);

			tickerService.addTicker(userId, "wecc", -amount, "竞猜投注", null);

			if (result.equalsIgnoreCase(info.getResult1())) {
				// 选择第一个答案
				info.setAmount1(info.getAmount1() + amount);
				info.setPeople1(info.getPeople1() + 1);
			} else {
				// 选择第二个答案
				info.setAmount2(info.getAmount2() + amount);
				info.setPeople2(info.getPeople2() + 1);
			}

			// 重新计算赔率
			if (info.getAmount1() > 0 && info.getAmount2() > 0) {
				double total = info.getAmount1() + info.getAmount2();
				info.setRate1(total / info.getAmount1());
				info.setRate2(total / info.getAmount2());
			}
			beanDao.save(info);

			return new GeneralResult<GuessInfo>().setValue(info);
		}
	}

	/**
	 * 查询用户竞猜记录
	 * 
	 * @param userId
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping(value = "/guess/user/log/query")
	@ResponseBody
	public ListResult<GuessLog> queryGuessLog(Long userId, Integer start, Integer limit) {

		return new ListResult<GuessLog>().setList(guessDao.queryGuessLog(userId, start, limit)).setTotal(guessDao.queryGuessLogCount(userId));
	}

	/**
	 * 胜率榜
	 * 
	 * @return
	 */
	@GetMapping(value = "/guess/winrate/rank")
	@ResponseBody
	public ListResult<User> queryWinRateRank() {

		return new ListResult<User>().setList(guessDao.queryWinRateRank());
	}

	/**
	 * 盈利榜
	 * 
	 * @return
	 */
	@GetMapping(value = "/guess/profit/rank")
	@ResponseBody
	public ListResult<User> queryProfitRank() {

		return new ListResult<User>().setList(guessDao.queryProfitRank());
	}

	/**
	 * 查询我的排行
	 * 
	 * @param userId
	 * @param type
	 *            1 查询盈利排行, 2 胜率排行
	 * @return
	 */
	@GetMapping(value = "/guess/my/rank")
	@ResponseBody
	public GeneralResult<Integer> getMyRank(Long userId, Integer type) {
		int rank = 0;
		User user = beanDao.quickQueryOneById(User.class, userId);
		if (type == 1) {
			rank = 1 + guessDao.countMyProfitRank(user.getProfit());
		} else {
			rank = 1 + guessDao.countMyWinRateRank(user.getWinRate());
		}

		return new GeneralResult<Integer>().setValue(rank);
	}
	
	/**
	 * 查询最新20条提现记录
	 * @param cid
	 * @return
	 */
	@GetMapping(value = "/guess/cash/log")
	@ResponseBody
	public ListResult<UserTickerLog> queryTopUserTickerLog(String cid){
		if(StringUtils.isEmpty(cid))
			throw new NoteException("cid 不能为空");
		
		return new ListResult<UserTickerLog>().setList(guessDao.queryTopGuessLog(cid));
	}

	// ------------------------------------------------------------机器人相关接口--------------------------------------------------------------------------------------
	/**
	 * 查询机器人列表
	 * 
	 * @param start
	 * @param limit
	 * @return
	 */
	@GetMapping(value = "/guess/robot/query")
	@ResponseBody
	public ListResult<User> queryRobot(Integer start, Integer limit) {

		return new ListResult<User>().setList(guessDao.queryRobot(start, limit)).setTotal(guessDao.queryGuessCount());
	}

}
